// 首页搜索
import React, { useEffect, useRef, useState } from 'react';
import { Button, Image, Input, Text, View } from '@tarojs/components';
import TitleBar from '@/src/components/titleBar';
import Taro from '@tarojs/taro';
import './index.less';
import { AtSearchBar, AtTabs, AtTabsPane } from 'taro-ui';
import 'taro-ui/dist/style/components/tabs.scss';
import HighlightText from '@/src/components/highLight';
import VedioItem from '@/src/components/vedioItem';
import store from '@/src/store';
import ArticleItem from '@/src/components/articleItem';
import CommentItem from '@/src/components/commentItem';

import blankImg from 'https://file.linkcook.cn/image/wineMiniProgram/home/brand.png';
import CommonBlank from '@/src/components/pageBlank';
import { observer } from 'mobx-react-lite';
import {
  homeSearchListFun,
  userSearchListFun,
} from '@/src/common/method/homeSearchFun';
import InfiniteScroll from '@/src/components/infiniteScroll';
import { UserSearch } from '@/src/components/userSearch';
import { netWorkErrorInfo } from '@/src/utils/constants';
// tab列表
const tabList = [
  { title: '综合', type: 'ALL' },
  { title: '动态', type: 'DYNAMIC' },
  { title: '文章', type: 'ARTICLE' },
  { title: '视频', type: 'VIDEO' },
  { title: '用户', type: 'USER' },
];
const homeSearch = () => {
  const pageSize = 10;
  const contentKind = 'CIGAR';
  const [maxPageNum, setMaxPageNum] = useState<number>(0);
  const [pageIndex, setPageIndex] = useState<number>(1);
  const [paddingTop, setPaddingTop] = useState<number>();
  const [outHeight, setOutHeight] = useState<any>();
  const [dataList, setDataList] = useState([]); //搜索列表
  const [userDataList, setUserDataList] = useState<any>([]); //搜索列表
  const [currentTab, setCurrentTab] = useState(0);
  const [loadingText, setLoadingText] = useState<any>('');
  const [searchValue, setSearchValue] = useState('');
  const [current, setCurrent] = useState(0);
  const [show, setShow] = useState(true); // 默认显示第一个div
  const [picNumber, setPicNumber] = useState(3);
  const [clickAble, setClickAble] = useState<boolean>(true); //是否可点击状态
  const [minPublishTime, setMinPublishTime] = useState<any>(null); //最小发布时间，用于下拉刷新时使用
  const [contentType, setContentType] = useState(tabList[0].type); // 重命名
  const [displayedData, setDisplayedData] = useState<any>([]); // 当前页显示的数据
  const [searchTrigger, setSearchTrigger] = useState(0);
  // 一级下拉刷新状态
  const [refresherTriggered, setRefresherTriggered] = useState(false);
  console.log(displayedData, '===displayedData');
  console.log(loadingText, pageIndex, maxPageNum, '===loadingText');

  useEffect(() => {
    const sysInfo = Taro.getSystemInfoSync();
    let statusBarHeight: any = sysInfo.statusBarHeight;
    setPaddingTop(statusBarHeight + 44);
    setOutHeight(`calc(100vh - ${statusBarHeight + 44}px)`);
    // setOutHeight(`calc(100vh - ${statusBarHeight}px)`);

    // setShow(false);
  }, []);
  //获取常规搜索列表
  const allSearchFun = (value: any) => {
    console.log(value, contentKind, contentType, 'value, pageIndex');
    homeSearchListFun({
      // pageNo: pageIndex,
      // pageSize: 10,
      // minPublishTime,
      contentKind: contentKind,
      contentType: contentType,
      pageNum: 1,
      pageSize: 100,
      searchWords: value,
    })
      .then((res: any) => {
        console.log(res, '===res');
        let result: any = [];
        setLoadingText('');
        setMaxPageNum(Math.ceil(res.totalSize / pageSize));
        setDataList(res.contentSearchVos);
        // const startIndex = (pageIndex - 1) * pageNum;
        // const endIndex = pageIndex * pageNum;
        // setDisplayedData(res.list.slice(startIndex, endIndex));
        // if (pageIndex === 1) {
        //   setDataList(displayedData);
        // } else {
        //   result = [...dataList, ...res.list];
        //   setDataList(result);
        // }
      })
      .catch((err: any) => {
        console.log(err, 'err==');
      });
  };
  // // 切割数据到当前页
  // useEffect(() => {
  //   const startIndex = (pageIndex - 1) * pageSize;
  //   const endIndex = pageIndex * pageSize;
  //   setDisplayedData(dataList.slice(startIndex, endIndex));
  // }, [pageIndex, dataList, pageSize]);
  // 初始化加载第一页
  useEffect(() => {
    const initialData = dataList.slice(0, pageSize);
    setDisplayedData(initialData);
    console.log(initialData, displayedData, '===displayedData2');
  }, [dataList, pageSize]);
  //用户搜索
  const userSearchFun = (value: any, pageIndex: number) => {
    console.log(value, pageIndex, '===用户搜索结果');
    userSearchListFun({
      searchWords: value,
      pageNo: pageIndex,
      pageSize: 10,
    }).then((res: any) => {
      console.log(res, '===用户搜索结果1');
      let result: any = [];
      setLoadingText('');
      setMaxPageNum(Math.ceil(res.totalCount / pageSize));
      if (pageIndex === 1) {
        setUserDataList([...res.list]);
        console.log(userDataList, res.list, '===用户搜索结果2');
      } else {
        result = [...dataList, ...res.list];
        setUserDataList(result);
      }
    });
  };
  // 处理输入
  const onChange = (value: any) => {
    setSearchValue(value);
    const homeSearchRegex: RegExp = /^[\u4e00-\u9fa5a-zA-Z0-9\s\-.'&()（）]*$/u;
    //有内容并且满足条件
    if (homeSearchRegex.test(value) && value.length > 0) {
      console.log('满足条件');
      allSearchFun(value);
      //有内容不满足条件
    } else if (value.length > 0) {
      Taro.showToast({
        title: '请输入中文、英文、数字',
        icon: 'none',
      });
      //没有内容
    } else if (value.length === 0) {
      setDataList([]);
    }
  };
  // 清除输入内容
  const handleClear = () => {
    setSearchValue('');
    setDataList([]);
  };
  //失去焦点方法
  const blurFun = () => {
    if (searchValue) {
      if (contentType === 'USER') {
        userSearchFun(searchValue, pageIndex);
        console.log('用户搜索失去焦点', searchValue, pageIndex);
      } else {
        console.log('综合搜索失去焦点', searchValue, pageIndex);
        allSearchFun(searchValue);
      }
    } else {
      setDataList([]);
    }
  };

  // 切换Tab
  const handleTabClick = (index) => {
    setDisplayedData([]);
    setUserDataList([]);
    setCurrent(index);
    setContentType(tabList[index].type); // 更新为对应 tab 的 type
    setPageIndex(1);
    // 强制触发搜索（解决相同 Tab 不触发问题）
    setSearchTrigger((v) => v + 1);
    console.log(index, contentType, 'index');
    // setMinPublishTime(null); // 重置最小发布时间，以便重新加载数据
    // setMinPublishTime("2025-07-30 00:00:00")
    // 如果已有搜索词，切换tab后立即搜索
    // if (searchValue.trim()) {
    //   if (index === 4) {
    //     userSearchFun(searchValue, pageIndex);
    //     console.log('用户搜索', searchValue, pageIndex);
    //   }
    //   else{
    //     console.log('综合搜索', searchValue, pageIndex);
    //   allSearchFun(searchValue);
    //   }

    // }
  };
  // 监控type的改变去搜索
  useEffect(() => {
    if (searchValue) {
      if (contentType === 'USER') {
        userSearchFun(searchValue, pageIndex);
        console.log('用户搜索失去焦点', searchValue, pageIndex);
      } else {
        console.log('综合搜索失去焦点', searchValue, pageIndex);
        allSearchFun(searchValue);
      }
    }
  }, [contentType, searchTrigger]);

  //跳转到文章详情
  const gotoDetail = (item: any, name: string) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    // 统一提取userId，兼容两种数据结构
    const userId = item.userInfoVo?.ucUserId || item.ucUserId;

    if (!userId) {
      console.error('Invalid user ID');
      return;
    }
    if (clickAble) {
      if (name === 'userCenter') {
        Taro.navigateTo({
          url: `/subPagesAccount/userCenter/index?contentKind=CIGAR&&contentType=ALL&&userId=${userId}`,
        });
      } else if (name === 'comment') {
        Taro.navigateTo({
          url: `/subPagesAccount/commentDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
        });
      } else if (name === 'article') {
        Taro.navigateTo({
          url: `/subPagesAccount/articleDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
        });
      } else {
        //跳转到视频详情
        Taro.navigateTo({
          url: `/subPagesAccount/vedioDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
        });
      }
    }
  };

  //用户搜索结果
  const userContent = () => {
    return (
      <View>
        {userDataList &&
          userDataList.map((item: any, index: any) => {
            return (
              <UserSearch
                gotoDetail={(item: any, name: any) => gotoDetail(item, name)}
                data={item}
              />
            );
          })}
      </View>
    );
  };
  //综合内容列表

  const contentList = () => {
    return (
      <View>
        {displayedData &&
          displayedData.map((item: any, index: any) => {
            return (
              <View key={`${item.contentType}-${index}`}>
                {item.contentType === 'DYNAMIC' && (
                  <CommentItem
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                    data={item}
                    mine={false}
                  />
                )}
                {item.contentType === 'ARTICLE' && (
                  <ArticleItem
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                    mine={false}
                    data={item}
                    // selectClick={() => console.log('')}
                  />
                )}
                {item.contentType === 'VIDEO' && (
                  <VedioItem
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                    mine={false}
                    data={item}
                    // home={true}
                    // selectClick={() => console.log('')}
                  />
                )}
              </View>
            );
          })}
      </View>
    );
  };
  //下拉查询数据
  const onEndReached = () => {
    if (loadingText === '加载中') {
      return false;
    }
    const index = pageIndex + 1;
    if (index > maxPageNum) {
      return false;
    }

    // setLoadingText('加载中...');
    const nextPage = pageIndex + 1;
    const startIndex = (nextPage - 1) * pageSize;
    const endIndex = nextPage * pageSize;
    const newData = dataList.slice(startIndex, endIndex);
    if (newData.length > 0) {
      setDisplayedData((prev) => [...prev, ...newData]);
      setPageIndex(index); // 只有成功加载时才递增页码
    }

    setLoadingText('');
    // return allSearchFun(searchValue);
  };

  //加载下一页
  const loadMore = () => {
    let val: any = false;
    if (loadingText === '' && onEndReached) {
      setLoadingText('加载中...');
      val = onEndReached();
    }
    // if (pageIndex * pageSize >= maxPageNum) return;
    // setPageIndex(prev => prev + 1);
    console.log('loadMore', val);
  };
  // 一级下拉刷新处理
  const handleRefreshFun = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('加载中...');
    setRefresherTriggered(true);
    //是否是首次下拉刷新
    if (searchValue) {
      if (contentType === 'USER') {
        userSearchFun(searchValue, pageIndex);
        console.log('用户搜索失去焦点', searchValue, pageIndex);
      } else {
        console.log('综合搜索失去焦点', searchValue, pageIndex);
        allSearchFun(searchValue);
      }
    } else {
      setDataList([]);
    }
    setTimeout(() => {
      setRefresherTriggered(false);
    }, 1000);
  };
  return (
    <View
      className="search"
      style={{ paddingTop: paddingTop, height: outHeight }}
      // height: `calc(100vh - ${store.commonStore.pageAreaTop}rpx - ${store.commonStore.safeAreaBottom}rpx)`,
      // paddingTop: `${store.commonStore.pageAreaTop}rpx`,
      // paddingBottom: `${store.commonStore.safeAreaBottom}rpx`,
    >
      <TitleBar showLeftBack={true} title="搜索"></TitleBar>
      <View className="search-body">
        <View className="home-search-box">
          <AtSearchBar
            placeholder="搜索文章动态、用户等"
            className="home-search-bar"
            actionName="取消"
            value={searchValue}
            showActionButton={true}
            onChange={(value) => onChange(value)}
            onActionClick={handleClear}
            onBlur={() => blurFun()}
            onFocus={() => setLoadingText('')}
          />
        </View>

        <View className="111">
          <AtTabs
            current={current}
            tabList={tabList}
            // onClick={(index) => setCurrent(index)}
            onClick={handleTabClick}
            className="search-tab"
          >
            <AtTabsPane current={current} index={0}>
              <View
                className="AtTabsPane-body"
                style={{
                  // height: `calc(100vh - ${store.commonStore.pageAreaTop}px - ${store.commonStore.safeAreaBottom}px - 96px)`,
                  // overflow: 'auto',
                  height: `calc(100vh - (112rpx + ${store.commonStore.pageAreaTop}rpx + ${store.commonStore.safeAreaBottom}rpx))`,
                  paddingBottom: `calc(${store.commonStore.safeAreaBottom}rpx)`,
                  overflow: 'auto',
                }}
              >
                <InfiniteScroll
                  hasMore={pageIndex < maxPageNum}
                  loadMore={async () => loadMore()}
                  dataList={dataList}
                  loading={loadingText === '' ? false : true}
                  content={contentList()}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                />
              </View>
            </AtTabsPane>
            <AtTabsPane current={current} index={1}>
              <View
                className="AtTabsPane-body"
                style={{
                  height: `calc(100vh - (112rpx + ${store.commonStore.pageAreaTop}rpx + ${store.commonStore.safeAreaBottom}rpx))`,
                  paddingBottom: `calc(${store.commonStore.safeAreaBottom}rpx)`,
                  overflow: 'auto',
                }}
              >
                <InfiniteScroll
                  hasMore={pageIndex < maxPageNum}
                  loadMore={async () => loadMore()}
                  dataList={dataList}
                  loading={loadingText === '' ? false : true}
                  content={contentList()}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                />
              </View>
            </AtTabsPane>
            <AtTabsPane current={current} index={2}>
              <View
                className="AtTabsPane-body"
                style={{
                  height: `calc(100vh - (112rpx + ${store.commonStore.pageAreaTop}rpx + ${store.commonStore.safeAreaBottom}rpx))`,
                  paddingBottom: `calc(${store.commonStore.safeAreaBottom}rpx)`,
                  overflow: 'auto',
                }}
              >
                <InfiniteScroll
                  hasMore={pageIndex < maxPageNum}
                  loadMore={async () => loadMore()}
                  dataList={dataList}
                  loading={loadingText === '' ? false : true}
                  content={contentList()}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                />
              </View>
            </AtTabsPane>
            <AtTabsPane current={current} index={3}>
              <View
                className="AtTabsPane-body"
                style={{
                  height: `calc(100vh - (112rpx + ${store.commonStore.pageAreaTop}rpx + ${store.commonStore.safeAreaBottom}rpx))`,
                  paddingBottom: `calc(${store.commonStore.safeAreaBottom}rpx)`,
                  overflow: 'auto',
                }}
              >
                <InfiniteScroll
                  hasMore={pageIndex < maxPageNum}
                  loadMore={async () => loadMore()}
                  dataList={displayedData}
                  loading={loadingText === '' ? false : true}
                  content={contentList()}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                />
              </View>
            </AtTabsPane>
            <AtTabsPane current={current} index={4}>
              <View
                className="AtTabsPane-body"
                style={{
                  height: `calc(100vh - (112rpx + ${store.commonStore.pageAreaTop}rpx + ${store.commonStore.safeAreaBottom}rpx))`,
                  paddingBottom: `calc(${store.commonStore.safeAreaBottom}rpx)`,
                  overflow: 'auto',
                }}
              >
                <InfiniteScroll
                  hasMore={pageIndex < maxPageNum}
                  loadMore={async () => loadMore()}
                  dataList={userDataList}
                  loading={loadingText === '' ? false : true}
                  content={userContent()}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                />
              </View>
            </AtTabsPane>
          </AtTabs>
          <CommonBlank
            visible={
              loadingText === '' &&
              searchValue.length > 0 &&
              (displayedData.length || userDataList.length) === 0
            }
            blank={
              'https://file.linkcook.cn/image/wineMiniProgram/exception/empty_search.png'
            }
            desc="抱歉，搜索无结果"
          />
        </View>
      </View>
    </View>
  );
};

export default observer(homeSearch);
